package com.ssish.saas.eccs.service;

import org.apache.commons.codec.binary.Base64InputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ssish.saas.eccs.util.OssConfig;
import com.ssish.saas.eccs.util.OssUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

@Component
public class OssService {

    @Value("${endpoint}")
    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }
    @Value("${accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }
    @Value("${accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }
    @Value("${bucketName}")
    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }
    @Value("${objectName}")
    public void setObjectName(String objectName) {
        this.objectName = objectName;
    }

    private static String endpoint;

    private static String accessKeyId;

    private static String accessKeySecret;

    private static String bucketName;

    private static String objectName;

    private OssConfig ossConfig;

    private void createConfig(){
        if(ossConfig!=null) return;
        ossConfig=new OssConfig();
        ossConfig.setEndpoint(endpoint);
        ossConfig.setAccessKeyId(accessKeyId);
        ossConfig.setAccessKeySecret(accessKeySecret);
        ossConfig.setBucketName(bucketName);
    }

    /**
     * 上传file
     * @param file
     * @param name name为路径与名称
     */
    public void upload(File file,String name){
        createConfig();
        ossConfig.setObjectName(this.objectName+name);
        OssUtils.upload(ossConfig,file);
    }

    /**
     * 上传imgbase64流
     * @param imgStr
     * @param name name为路径与名称
     */
    public void upload(String imgStr,String name){
        createConfig();
        ossConfig.setObjectName(this.objectName+name);
        OssUtils.upload(ossConfig,new Base64InputStream(new ByteArrayInputStream(imgStr.getBytes())));
    }

    /**
     * 上传file
     * @param is
     * @param name name为路径与名称
     */
    public void upload(InputStream is, String name){
        createConfig();
        ossConfig.setObjectName(this.objectName+name);
        OssUtils.upload(ossConfig,is);
    }

    /**
     * 下载file
     * @param name
     * @param name name为路径与名称
     */
    public InputStream get(String name){
        createConfig();
        ossConfig.setObjectName(this.objectName+name);
        return OssUtils.get(ossConfig);
    }

    public void delete(String name){
        createConfig();
        ossConfig.setObjectName(this.objectName+name);
        OssUtils.delete(ossConfig);
    }
    public void listBuckets(){
        createConfig();
        ossConfig.setObjectName(this.objectName);
        OssUtils.listBuckets(ossConfig);
    }

}
